#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    ui->port_line_edit->setText("8899");
    setWindowTitle("服务器");

    status_label_ = new QLabel;
    status_label_->setText("未连接");
    ui->statusbar->addWidget(new QLabel("连接状态:"));
    ui->statusbar->addWidget(status_label_);
    ui->send_msg_button->setEnabled(false);

    tcp_server_ = new QTcpServer(this);
    tcp_socket_ = nullptr;

    connect(tcp_server_, &QTcpServer::newConnection, this, &MainWindow::OnNewConnect);
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::BeginListen()
{
    ushort port = ui->port_line_edit->text().toUShort();
    tcp_server_->listen(QHostAddress::Any, port);
    ui->start_listen_button->setText("停止监听");
}

void MainWindow::CloseListen()
{
    tcp_socket_->close();
    tcp_socket_->deleteLater();

    tcp_server_->close();
    ui->start_listen_button->setText("开始监听");
}

void MainWindow::OnNewConnect()
{
    tcp_socket_ = tcp_server_->nextPendingConnection();
    status_label_->setText("已连接");
    ui->send_msg_button->setEnabled(true);
    connect(tcp_socket_, &QTcpSocket::readyRead, this, &MainWindow::OnReadyRead);
    connect(tcp_socket_, &QTcpSocket::disconnected, this, &MainWindow::OnDisConnect);
    connect(tcp_socket_, &QTcpSocket::stateChanged, this, [=](QAbstractSocket::SocketState socketState) {
        qDebug() << socketState;
    });
}

void MainWindow::OnDisConnect()
{
    tcp_socket_->close();
    tcp_socket_->deleteLater();
    tcp_socket_= nullptr;
    status_label_->setText("未连接");
    ui->send_msg_button->setEnabled(false);
}

void MainWindow::OnReadyRead()
{
    QByteArray data = tcp_socket_->readAll();
    ui->log_text_edit->append("Client say:" + data);
}

void MainWindow::on_start_listen_button_clicked() {
    if(!tcp_server_->isListening()) {
        BeginListen();
    } else {
        CloseListen();
    }
}

void MainWindow::on_send_msg_button_clicked()
{
    if(nullptr == tcp_socket_ || !tcp_socket_->isOpen() || !tcp_socket_->isWritable()) {
        return;
    }

    QString msg = ui->send_msg_text_edit->toPlainText();

    tcp_socket_->write(msg.toUtf8());
    ui->log_text_edit->append("Server say:" + msg);

}
